//
//  WriteMarkViewController.m
//  图片故事
//
//  Created by 大帅逼 on 16/3/5.
//  Copyright © 2016年 helloApp. All rights reserved.
//

#import "WriteMarkViewController.h"
#import "Header.h"
#import "FilterCollectionViewCell.h"
#import "LocaData.h"

@interface WriteMarkViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>{

    BOOL        _isShowMore;
    NSInteger   _selectIndex;
    NSInteger   _oldSelectIndex;
}

@property(nonatomic,strong) UIButton            *cancelBtn;
@property(nonatomic,strong) UIImageView         *contextImageView;
@property(nonatomic,strong) UICollectionView    *markCollectionView;
@property(nonatomic,strong) UIView              *markView;
@property(nonatomic,strong) UIView              *toolsView;
@property(nonatomic,strong) UIImage             *oldImage;
@property(nonatomic,strong) UIImageView         *markImageView;
@property(nonatomic,strong) NSMutableArray      *markViewArray;
@property(nonatomic,strong) NSMutableArray      *markCancelBtn;

@end

@implementation WriteMarkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化页面
    [self initView];
}

#pragma mark -- 页面初始化相关
- (void) initView {

     _oldImage = _loadImage;
    
    _isShowMore = NO;
    
    _markViewArray = [[NSMutableArray alloc] init];
    
    _markCancelBtn = [[NSMutableArray alloc] init];
    
    [self.view setBackgroundColor:[UIColor blackColor]];
    
    // 添加取消按钮
    [self.view addSubview:self.cancelBtn];
    
    // 添加图片视图
    [self.view addSubview:self.contextImageView];
    
    [self.contextImageView setImage:_loadImage];
    
    // 添加工具视图
    [self.view addSubview:self.toolsView];
    
    // 添加标签表格视图
    [self.view addSubview:self.markCollectionView];
}

#pragma mark -- 点击事件相关设置
- (void) action_cancelClickEvent : (UIButton *) sender{

    UIView *markView = [_markViewArray objectAtIndex:_selectIndex];
    
    [markView removeFromSuperview];
}

- (void) action_oldBtnClickEvent {

    for (int i = 0; i < [_markViewArray count]; i++) {
        
        UIView *markView = [_markViewArray objectAtIndex:i];
        
        [markView removeFromSuperview];
    }
}

- (void) action_cancelBtnClickEvent {

    [self.navigationController popViewControllerAnimated:YES];
}

- (void) action_moreBtnClickEvent {

    if (!_isShowMore) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            [self.view setFrame:CGRectMake(0, - My_Height(220), SCREEN_W, SCREEN_H + 220)];
        } completion:^(BOOL finished) {
            
            _isShowMore = YES;
        }];
    }else {
    
        [UIView animateWithDuration:0.3 animations:^{
            
            [self.view setFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        } completion:^(BOOL finished) {
            
            _isShowMore = NO;
        }];
    }
}

- (void) action_createBtnClickEvent {
    
    if ([_markViewArray count] == 0) {
        
        // 作为属性传值
        if (self.callBack != nil) {
            
            self.callBack(_loadImage);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else {
        UIButton *cancelBtn = [_markCancelBtn objectAtIndex:_selectIndex];
        
        [cancelBtn setAlpha:0];
        
        UIView *markView = [_markViewArray objectAtIndex:_selectIndex];
        
        [markView.layer setBorderColor:[UIColor clearColor].CGColor];
        
        [self composeMarkImageWithContextImage];
        
        [markView setAlpha:0];
    }
}

// 将水印和图片合成在一起
- (void) composeMarkImageWithContextImage {
    
    // 现获取整个屏幕的截图
    UIImage *markImage = [self snapshot:self.view];
    
    CGPoint point = self.contextImageView.center;
    
    CGSize size = [self getSize];
    
//    NSLog(@"%lf,%lf,%lf,%lf",point.x,point.y,size.width,size.height);
    
    CGImageRef sourceImageRef = [markImage CGImage];
    
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, CGRectMake((point.x - size.width / 2) * 2, (point.y - size.height / 2) * 2, size.width * 2, size.height * 2));
    
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    // 作为属性传值
    if (self.callBack != nil) {
        
        self.callBack(newImage);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGSize) getSize {
    CGSize size;

    if (_loadImage.size.width > _loadImage.size.height && _loadImage.size.width > SCREEN_W) {
        
        size = CGSizeMake(SCREEN_W, _loadImage.size.height * (SCREEN_W / _loadImage.size.width));
    }else if (_loadImage.size.height > _loadImage.size.width && _loadImage.size.height > SCREEN_H){
    
        size = CGSizeMake(_loadImage.size.width * ((SCREEN_H - My_Height(260)) / _loadImage.size.height), SCREEN_H - My_Height(260));
        
    }else if(_loadImage.size.width <= SCREEN_W && _loadImage.size.height <= SCREEN_H - My_Height(260)){
    
        if (_loadImage.size.width > _loadImage.size.height ) {
            
            size = CGSizeMake(SCREEN_W, _loadImage.size.height * (SCREEN_W / _loadImage.size.width));
        }else if (_loadImage.size.height > _loadImage.size.width){
            
            size = CGSizeMake(_loadImage.size.width * ((SCREEN_H - My_Height(260)) / _loadImage.size.height), SCREEN_H - My_Height(260));
        }else {
        
            size = CGSizeMake(SCREEN_W, SCREEN_W);
        }
    }
    
    return size;
}

- (UIImage *)snapshot:(UIView *)view

{
    
    UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES,0);
    
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}

- (void) action_selectClickEvent : (UIButton *) sender {

    _selectIndex = sender.tag - 200;
    
    [self action_addMarkWithIndex:_selectIndex];
    
    [self upSelectMarkView];
    
    _oldSelectIndex = sender.tag - 200;
}

- (void) upSelectMarkView {
    
    UIView *oldMarkView = [_markViewArray objectAtIndex:_oldSelectIndex];
    
    [self hideBoardWithOldMarkView:oldMarkView];
    
    UIView *newMarkView = [_markViewArray objectAtIndex:_selectIndex];
    
    [self showBoardWithNewMarkView:newMarkView];
}

- (void) hideBoardWithOldMarkView : (UIView *) oldView {
    
    UIButton *oldCancelBtn = [_markCancelBtn objectAtIndex:_oldSelectIndex];
    
    [oldCancelBtn setAlpha:0];

    [oldView.layer setBorderColor:[[UIColor clearColor] CGColor]];
}

- (void) showBoardWithNewMarkView : (UIView *) newView {
    
    UIButton *newCancelBtn = [_markCancelBtn objectAtIndex:_selectIndex];
    
    [newCancelBtn setAlpha:1];
    
    [newView.layer setBorderColor:[[UIColor yellowColor] CGColor]];
}

- (void) action_addMarkWithIndex : (NSInteger) index {
    
    //创建捏合手势
    UIPinchGestureRecognizer *pinchGestrue = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(gestEvent:)];
    
    [self.view addGestureRecognizer:pinchGestrue];
    
    //创建拖动手势
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestEvent:)];
    
    [[_markViewArray objectAtIndex:_selectIndex] addGestureRecognizer:panGesture];
    
    // 创建旋转手势
    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(gestEvent:)];
    
    [self.view addGestureRecognizer:rotationGesture];
}

#pragma mark --手势响应方法
- (void) gestEvent : (UIGestureRecognizer *)sender{
    __weak typeof(self) weakSelf = self;
    
    UIView *markView = [_markViewArray objectAtIndex:_selectIndex];
    
    if([sender isKindOfClass:[UIPinchGestureRecognizer class]]){
        //强转手势
        UIPinchGestureRecognizer *pinchGesture = (UIPinchGestureRecognizer *) sender;
        if (pinchGesture.state == UIGestureRecognizerStateChanged) {
            
            //缩放图片(改变视图的形变属性transfrom)
            //参数为缩放比例 0 - 1
            //CGAffineTransformMakeScale只能缩放一次
            markView.transform = CGAffineTransformScale(markView.transform, pinchGesture.scale, pinchGesture.scale);
            
            //初始化缩放比例
            pinchGesture.scale = 1;
        }
        
    }else if([sender isKindOfClass:[UIPanGestureRecognizer class]]){
        //拖动手势
        UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *) sender;
        if (panGesture.state == UIGestureRecognizerStateChanged) {
            
            //手势改变的时候
            //获得手势当前移动点
            CGPoint movePoint = [panGesture translationInView:weakSelf.view];
            
            //获得视图当前的中心点
            CGPoint currPoint = markView.center;
            
            markView.center = CGPointMake(currPoint.x + movePoint.x, currPoint.y + movePoint.y);
            //初始化移动值的增量
            [panGesture setTranslation:CGPointZero inView:weakSelf.view];
        }
    }else if ([sender isKindOfClass:[UIRotationGestureRecognizer class]]){
    
        UIRotationGestureRecognizer *rotationGesture = (UIRotationGestureRecognizer *) sender;
        
        if (rotationGesture.state == UIGestureRecognizerStateBegan || rotationGesture.state == UIGestureRecognizerStateChanged) {
            
            markView.transform = CGAffineTransformRotate(markView.transform, rotationGesture.rotation);
            
            [rotationGesture setRotation:0];
        }
    }
}


#pragma mark -- 水印表格视图数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [[LocaData readMarkArray] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    FilterCollectionViewCell *markCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mark_cell" forIndexPath:indexPath];
    
    [markCell.filterImageView setImage:[UIImage imageNamed:[[LocaData readMarkArray] objectAtIndex:indexPath.row]]];
    
    [markCell.nameLabel setBackgroundColor:[UIColor clearColor]];
    
    return markCell;
}

#pragma mark -- 水印表格视图代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    UIImage *markImage = [UIImage imageNamed:[[LocaData readMarkArray] objectAtIndex:indexPath.row]];
    
    [self.view addSubview:self.markView];
    
    [_markImageView setImage:markImage];
    
    [self action_addMarkWithIndex:indexPath.row];
    
    [self upSelectMarkView];
    
    _oldSelectIndex = _selectIndex;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(My_Height(80), My_Height(100));
}

#pragma mark -- 懒加载
- (UIButton *)cancelBtn {

    if (!_cancelBtn) {
        
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_cancelBtn setFrame:CGRectMake(My_Width(20), My_Height(40), My_Height(30), My_Height(30))];
        
        [_cancelBtn setImage:[UIImage imageNamed:@"Cancel_icon"] forState:UIControlStateNormal];
        
        [_cancelBtn addTarget:self action:@selector(action_cancelBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _cancelBtn;
}

- (UIImageView *)contextImageView {

    if (!_contextImageView) {
        
        _contextImageView = [[UIImageView alloc] init];
        
        [_contextImageView setFrame:CGRectMake(0, My_Height(90), SCREEN_W, SCREEN_H - My_Height(260))];
        
        [_contextImageView setContentMode:UIViewContentModeScaleAspectFit];
    }
    
    return _contextImageView;
}

- (UIView *)toolsView {

    if (!_toolsView) {
        
        _toolsView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - My_Height(160), SCREEN_W, My_Height(50))];
        
        [_toolsView setBackgroundColor:[UIColor colorWithWhite:0.8 alpha:0.2]];
        
        UIButton *oldBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [oldBtn setFrame:CGRectMake(My_Width(20), My_Height(15),My_Height(40), My_Height(20))];
        
        [oldBtn setTitle:@"还原" forState:UIControlStateNormal];
        
        [oldBtn.titleLabel setTextColor:[UIColor whiteColor]];
        
        [oldBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        
        [oldBtn addTarget:self action:@selector(action_oldBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
        
        [_toolsView addSubview:oldBtn];
        
        UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [moreBtn setBounds:CGRectMake(0, 0, My_Height(30), My_Height(30))];
        
        [moreBtn setCenter:CGPointMake(SCREEN_W / 2, My_Height(25))];
        
        [moreBtn setImage:[UIImage imageNamed:@"more_icon"] forState:UIControlStateNormal];
        
        [moreBtn addTarget:self action:@selector(action_moreBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
        
        [_toolsView addSubview:moreBtn];
        
        UIButton *createMark = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [createMark setFrame:CGRectMake(SCREEN_W - My_Width(50), My_Height(10), My_Width(30), My_Height(30))];
        
        [createMark setImage:[UIImage imageNamed:@"save_icon"] forState:UIControlStateNormal];
        
        [createMark.titleLabel setTextColor:[UIColor whiteColor]];
        
        [createMark.titleLabel setFont:[UIFont systemFontOfSize:12]];
        
        [createMark addTarget:self action:@selector(action_createBtnClickEvent) forControlEvents:UIControlEventTouchUpInside];
        
        [_toolsView addSubview:createMark];
    }
    
    return _toolsView;
}

- (UICollectionView *)markCollectionView {

    if (!_markCollectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setMinimumInteritemSpacing:0.0];
        
        [layout setMinimumLineSpacing:5.0];
        
        _markCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, SCREEN_H - My_Height(110), SCREEN_W, My_Height(330)) collectionViewLayout:layout];
        
        [_markCollectionView registerClass:[FilterCollectionViewCell class] forCellWithReuseIdentifier:@"mark_cell"];
        
        [_markCollectionView setBackgroundColor:[UIColor colorWithWhite:0.8 alpha:0.2]];
        
        [_markCollectionView setShowsHorizontalScrollIndicator:NO];
        
        [_markCollectionView setDataSource:self];
        
        [_markCollectionView setDelegate:self];
    }
    
    return _markCollectionView;
}

- (UIView *)markView {
    
    _markView = [[UIView alloc] init];
    
    [_markView setFrame:CGRectMake(SCREEN_W / 2 - My_Width(40), (SCREEN_H - My_Height(260)) / 2 - My_Height(50), My_Width(80), My_Height(100))];
    
    [_markView.layer setBorderWidth:1.0];
    
    [_markView.layer setBorderColor:[UIColor clearColor].CGColor];
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [selectBtn setFrame:CGRectMake(0, 0, My_Width(80), My_Height(100))];
    
    [selectBtn addTarget:self action:@selector(action_selectClickEvent : ) forControlEvents:UIControlEventTouchUpInside];
    
    [_markView addSubview:selectBtn];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [cancelBtn setBounds:CGRectMake(0, 0, My_Height(20), My_Height(20))];
    
    [cancelBtn setCenter:CGPointMake(My_Height(10), My_Height(90))];
    
    [cancelBtn setImage:[UIImage imageNamed:@"mark_cancel"] forState:UIControlStateNormal];
    
    [cancelBtn addTarget:self action:@selector(action_cancelClickEvent : ) forControlEvents:UIControlEventTouchUpInside];
    
    [cancelBtn setTag:_markViewArray.count - 1 + 300];
    
    [_markCancelBtn addObject:cancelBtn];
    
    [_markView addSubview:cancelBtn];
    
    _markImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, My_Width(80), My_Height(100))];
    
    [_markView addSubview:_markImageView];
    
    [_markViewArray addObject:_markView];
    
    [selectBtn setTag:_markViewArray.count - 1 + 200];
    
    _selectIndex = _markViewArray.count - 1;

    return _markView;
}

#pragma mark -- 页面初始化
- (void)viewWillAppear:(BOOL)animated {

    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {

    [self.navigationController setNavigationBarHidden:NO];
}

@end
